package nickthissen.iracing.networking;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import nickthissen.iracing.common.Constants;

public class Params extends HashMap<String, Object>
{	
	private HashMap<String, JSONObject> objectEntries;
	
	public Params()
	{
		objectEntries = new HashMap<String, JSONObject>();
	}

    public static Params createServiceParams()
    {
        Params p = new Params();
        p.put("appversion", Constants.VERSION);
        return p;
    }
	
	public void putObject(String key, JSONObject value)
	{
		this.objectEntries.put(key, value);
	}

//    public RequestParams toRequestParams()
//    {
//        RequestParams p = new RequestParams();
//        for (Entry<String, Object> entry : this.entrySet())
//        {
//            p.put(entry.getKey(), entry.getValue().toString());
//        }
//
//        return p;
//    }
		
	public JSONObject toJson() throws JSONException
	{
	    JSONObject json = new JSONObject();
	    
	    // Primitive types
	    for (Map.Entry<String, Object> p : this.entrySet())
	    {
	    	json.put(p.getKey(), p.getValue());
	    }
	    
	    // Complex objects
	    for (Map.Entry<String, JSONObject> p : objectEntries.entrySet())
	    {
	    	json.put(p.getKey(), p.getValue());
	    }
	    
	    return json;
	}
	
	public String appendToUrl(String url) throws Exception
	{
		if (objectEntries.size() > 0)
			throw new Exception("Cannot send complex object parameters with HTTP GET.");
		
		List<NameValuePair> values = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> p : this.entrySet())
		{
			values.add(new BasicNameValuePair(p.getKey(), p.getValue().toString()));
		}
		
		String params = URLEncodedUtils.format(values, "utf-8");
		return url + "?" + params;
	}
	
}
